package com.gitee.feizns.explore.data_structure.tree.bs.easy;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author feizns
 * @since 2020/3/9
 */
public class LevelOrder {

    private static TreeNode create() {
        TreeNode ret = new TreeNode(0);
        ret.left = new TreeNode(1);
        ret.right = new TreeNode(2);
        return ret;
    }

    public static void main(String[] args) {
        System.out.println(new LevelOrder().levelOrder(create()));
    }

    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<TreeNode>> ret = new LinkedList<>();
        if ( root != null ) {
            int level = 0;
            ret.add(Arrays.asList(root));
            List<TreeNode> prev;
            while( level < ret.size() && !(prev = ret.get(level)).isEmpty() ) {
                List<TreeNode> curt = new LinkedList<>();
                for(TreeNode n : prev) {
                    if (n.left != null)
                        curt.add(n.left);
                    if (n.right != null)
                        curt.add(n.right);
                }
                if ( !curt.isEmpty() )
                    ret.add(curt);
                level++;
            }
        }
        return ret.parallelStream().map(l -> l.parallelStream().map(n -> n.val).collect(Collectors.toList())).collect(Collectors.toList());
    }

}
